import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, asyncRoutes, constantRoutes, } from '@/router'
import router from '@/router'
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    buttons: [],
    roles: [],
    routes: [],
    resultRouters: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINOFO: (state, userInfo) => {
    state.name = userInfo.name
    state.avatar = userInfo.avatar
    state.buttons = userInfo.buttons
    state.roles = userInfo.roles
    state.routes = userInfo.routes
  },
  SET_RESULTROURER: (state, result) => {
    state.resultRouters = [...constantRoutes, ...result]
    router.addRoutes(state.resultRouters)
  }
}

//筛选路由权限
function getRouter(routes, asyncRoutes) {
  return asyncRoutes.filter(item => {
    if (routes.indexOf(item.name) != -1) {
      if (item.children && item.children.length) {
        getRouter(routes, item.children)
      }
      return true
    }
  })
}

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const { username, password } = userInfo
    let result = await login({ username: username.trim(), password: password })
    if (result.code == 20000) {
      const { data } = result
      commit('SET_TOKEN', data.token)
      setToken(data.token)
      return 'ok';
    } else {
      return new Promise(new Error('faile'))
    }
  },



  // get user info
  async getInfo({ commit, state }) {
    let result = await getInfo(state.token)
    if (result.code == 20000) {
      const { data } = result
      if (!data) {
        return reject('请重试重新登录!')
      }
      console.log(data)
      commit('SET_USERINOFO', data)
      commit('SET_RESULTROURER', getRouter(data.routes, asyncRoutes))
      return 'ok';
    } else {
      return new Promise(new Error('faile'))
    }
  },

  // user logout
  async logout({ commit, state }) {
    let result = await logout(state.token)
    if (result.code == 20000) {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      return 'ok';
    } else {
      return new Promise(new Error('faile'))
    }
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

